package com.ys.service.storage.impl;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgPurchaseInStorage;
import com.ys.entity.storage.TccAssembleError;
import com.ys.mapper.purchase.TcgPurchaseInStorageMapper;
import com.ys.mapper.storage.TccAssembleErrorMapper;
import com.ys.service.storage.TccAssembleErrorService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 组装报错单
 */
@Service("tccAssembleErrorService")
public class TccAssembleErrorServiceImpl implements TccAssembleErrorService {
	private static final Logger logger = LoggerFactory.getLogger(TccAssembleErrorServiceImpl.class);

	@Autowired
	private TccAssembleErrorMapper tccAssembleErrorMapper;

	@Autowired
	private CheckUtil checkUtil;

	//@Autowired
	//private ProductMapper productMapper;

	@Autowired
	private CommonApiService<TccAssembleError> commonApiService;

	@Autowired
	private TcgPurchaseInStorageMapper tcgPurchaseInStorageMapper;

	/**
	 * 新增组装报错单
	 * @param assembleItemId 组装单子件明细表id（TCC_AssembleItem）
	 * @param subAssembleLostNum 子件缺失数量
	 */
	@Override
	public TccAssembleError add(Long assembleItemId,int subAssembleLostNum) throws Exception{
		logger.info("新增传参:"+assembleItemId+";"+subAssembleLostNum);
		TccAssembleError entity =new TccAssembleError();
		entity.setStatus(1);//状态
		//获取单号
		String bid = commonApiService.getCommonNextBid(MenuId.TCC_AssembleError);
		//单号
		entity.setBid(bid);
		entity.setHandleStatus(0);//处理状态（0未处理、1不处理、2补发货、3已发货）
		entity.setAssembleItemId(assembleItemId);
		entity.setSubAssembleLostNum(subAssembleLostNum);
		entity.setInStorageStatus(0);
		//新增
		tccAssembleErrorMapper.insert(entity);
		return entity;
	}



	//报错处理
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R errorHandle(Map<String, Object> params) throws Exception{
		if(checkUtil.isNullByObject(params.get("id"))){
			return R.error("操作失败，id信息为空");
		}
		if(checkUtil.isNullByObject(params.get("handleStatus"))){
			return R.error("操作失败，处理状态信息为空");
		}
		int handleStatus = Integer.parseInt(params.get("handleStatus").toString());
		if(handleStatus!=1 && handleStatus!=2){
			return R.error("操作失败，未知的处理状态");
		}
		TccAssembleError entity =new TccAssembleError().setId(Long.parseLong(params.get("id").toString())).queryFirst();
		if(entity!=null && entity.getBid()!=null){
			if(entity.getHandleStatus()==3){
				return R.error("\"已发货\"的组装报错单不做处理");
			}
			entity.setHandleTime(new Date());//处理时间
			entity.setHandleStatus(handleStatus);//处理状态（0未处理、1不处理、2补发货、3已发货）
			tccAssembleErrorMapper.update(entity);//修改
		}else {
			return R.error("操作失败，未查询到对应的报错单信息");
		}

		return R.ok();
	}


	//预入库
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R preStorage(Map<String, Object> params) throws Exception{
		if(checkUtil.isNullByObject(params.get("id"))){
			return R.error("操作失败，id信息为空");
		}
		if(checkUtil.isNullByObject(params.get("estimatedArrivalTime"))){
			return R.error("操作失败，预计入库时间信息为空");
		}
		if(checkUtil.isNullByObject(params.get("logisticsMode"))){
			return R.error("操作失败，物流方式信息为空");
		}
		if(checkUtil.isNullByObject(params.get("trackingNumber"))){
			return R.error("操作失败，物流单号信息为空");
		}
		//TccAssembleError entity =new TccAssembleError().setId(Long.parseLong(params.get("id").toString())).queryFirst();
		//获取数据详情
		Map<String, Object> info = getDeatil(Long.parseLong(params.get("id").toString()));
		if(info!=null){
			if(!info.get("handleStatus").toString().equals("2")){
				return R.error("只有\"补发货\"的组装报错单才可预入库");
			}
			//1、触发采购入库
			TcgPurchaseInStorage tcgPurchaseInStorage = new TcgPurchaseInStorage();
			tcgPurchaseInStorage.setBid(commonApiService.getCommonNextBid(MenuId.TCG_PurchaseInStorage));//单号
			if(checkUtil.isNotNullByObject(info.get("bid")))tcgPurchaseInStorage.setPurchasePreStorageBid(info.get("bid").toString());//采购预入库单号=>报错单单号
			if(checkUtil.isNotNullByObject(info.get("contractBid")))tcgPurchaseInStorage.setPurchaseContractBid(info.get("contractBid").toString());//采购合同单号
			if(checkUtil.isNotNullByObject(info.get("companyVid")))tcgPurchaseInStorage.setCompanyVid(info.get("companyVid").toString());//购买方公司编码
			if(checkUtil.isNotNullByObject(info.get("partnerBankInfoId")))tcgPurchaseInStorage.setPartnerBankInfoId(info.get("partnerBankInfoId").toString());//供应方公司银行信息id
			tcgPurchaseInStorage.setEstimatedArrivalTime(params.get("estimatedArrivalTime").toString());//预计入库时间
			tcgPurchaseInStorage.setLogisticsMode(params.get("logisticsMode").toString());//物流方式
			tcgPurchaseInStorage.setTrackingNumber(params.get("trackingNumber").toString());//物流单号
			if(checkUtil.isNotNullByObject(info.get("appointOrderBid")))tcgPurchaseInStorage.setPurchaseAppointOrderBid(info.get("appointOrderBid").toString());//预约采购单号
			if(checkUtil.isNotNullByObject(info.get("vgsbm")))tcgPurchaseInStorage.setVgsbm(info.get("vgsbm").toString());//运营公司编码
			if(checkUtil.isNotNullByObject(info.get("productCode")))tcgPurchaseInStorage.setProductCode(info.get("productCode").toString());//商品编码
			if(checkUtil.isNotNullByObject(info.get("productName")))tcgPurchaseInStorage.setProductName(info.get("productName").toString());//商品名称
			if(checkUtil.isNotNullByObject(info.get("codeMerge")))tcgPurchaseInStorage.setCodeMerge(info.get("codeMerge").toString());//合并商品编码
			if(checkUtil.isNotNullByObject(info.get("subCode")))tcgPurchaseInStorage.setSubCode(info.get("subCode").toString());//子件编码
			if(checkUtil.isNotNullByObject(info.get("subName")))tcgPurchaseInStorage.setSubName(info.get("subName").toString());//子件名称
			if(checkUtil.isNotNullByObject(info.get("subCodeMerge")))tcgPurchaseInStorage.setSubCodeMerge(info.get("subCodeMerge").toString());//子件合并编码
			if(checkUtil.isNotNullByObject(info.get("subBomNumber")))tcgPurchaseInStorage.setSubBomNumber(new Integer(info.get("subBomNumber").toString()));//子件BOM数量
			if(checkUtil.isNotNullByObject(info.get("subPurchasePrice")))tcgPurchaseInStorage.setSubPurchasePrice(new BigDecimal(info.get("subPurchasePrice").toString()));//子件采购单价
			if(checkUtil.isNotNullByObject(info.get("subAssembleLostNum")))tcgPurchaseInStorage.setSubStorageNum(new Integer(info.get("subAssembleLostNum").toString()));//子件入库数量、子件缺失数量
			tcgPurchaseInStorage.setStorageStatus(0);//入库状态
			tcgPurchaseInStorage.setAssembledStatus(0);//组装状态
			tcgPurchaseInStorage.setDocumentSource(1);//单据来源(0.入库单|1.组装报错)
			tcgPurchaseInStorage.setPurchasePreStorageSonId(Long.parseLong(info.get("purchasePreStorageSonId").toString()));//采购预入库子件id、报错单id
			tcgPurchaseInStorage.setPurchaseAppointOrderProductComponentId(Long.parseLong(info.get("appointOrderComponentId").toString()));//预约采购商品子件id
			tcgPurchaseInStorage.setStatus(0);//状态
			tcgPurchaseInStorageMapper.insert(tcgPurchaseInStorage);

			//2、处理状态变为”已发货“、同步更新处理时间
			TccAssembleError entity = new TccAssembleError();
			entity.setId(Long.parseLong(params.get("id").toString()));
			entity.setHandleTime(new Date());//处理时间
			entity.setHandleStatus(3);//处理状态（0未处理、1不处理、2补发货、3已发货）
			entity.setEstimatedArrivalTime(params.get("estimatedArrivalTime").toString());//预计入库时间
			entity.setLogisticsMode(params.get("logisticsMode").toString());//物流方式
			entity.setTrackingNumber(params.get("trackingNumber").toString());//物流单号
			tccAssembleErrorMapper.update(entity);//修改
		}else {
			return R.error("操作失败，未查询到报错单信息");
		}
		return R.ok();
	}


	//根据id获取数据详情
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public Map<String,Object> getDeatil(Long id) throws Exception{
		TccAssembleError cond = setSeachSqlByCommon(new TccAssembleError());
		Map<String,Object> extraParam = cond
				.setId(id)
				.queryFirstMap();
		return  extraParam;
	}


	//设置查询sql
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public TccAssembleError setSeachSqlByCommon(TccAssembleError cond) throws Exception{
		cond
				.addLeftJoin("TCC_AssembleItem B ON B.Id = A.AssembleItemId")//组装单子件明细表
				.addField("B.SubAssembleLeftNum AS subAssembleLeftNum")//子件组装剩余数量

				.addLeftJoin("TCC_Assemble AB ON AB.Bid = B.Pbid")//组装单
				.addField("AB.Bid assembleBid")//商品组装单号
				.addField("AB.ParentAssembleNumber parentAssembleNumber")//母件组装数量
				.addField("AB.ParentSinglePrice parentSinglePrice")//母件采购单价

				.addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = B.AppointOrderComponentId")//预约采购管理子件表
				.addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
				.addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
				.addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

				.addField("PPC.Bid AS appointOrderBid")//预约采购单单号
				.addField("PPC.Vgsbm AS vgsbm")//运营公司编码
				.addField("OCA.Vgsjc AS vgsjc")//运营公司简称
				.addField("PC.ProductCode AS productCode")//商品编码
				.addField("PC.ProductName AS productName")//商品名称
				.addField("PC.CodeMerge AS codeMerge")//合并商品编码
				.addField("PC.ReserveNumber AS reserveNumber")//母件预约数量、母件采购数量
				.addField("C.Id AS appointOrderComponentId")//子件编码
				.addField("C.SubCode AS subCode")//子件编码
				.addField("C.SubName AS subName")//子件名称
				.addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码

				.addLeftJoin("TCG_PurchaseAppointOrder O ON O.Id = AB.AppointOrderId ")//预约采购管理表
				.addLeftJoin("TB_CompanyInfo CI ON CI.Vid = O.CompanyVid ")//公司信息
				.addField("O.CompanyVid AS companyVid")
				.addField("CI.Vname AS vname")//购买方公司名称

				.addLeftJoin("TCG_PurchaseContractItem PCI ON PCI.OrderProductComponentId = C.Id")//采购合同单子表
				.addLeftJoin("TCG_PurchaseContract PPCI ON PPCI.Bid = PCI.Pbid")//采购合同单
				.addField("PPCI.Bid AS contractBid")//采购合同单号
				.addField("PCI.SubBomNumber AS subBomNumber")//子件BOM数量
				.addField("PCI.SubPurchasePrice AS subPurchasePrice")//子件采购单价

				.addLeftJoin("TCG_PurchaseInStorage PPSS ON PPSS.Id = B.PurchaseStorageId")//采购入库单
				.addField("PPSS.PurchasePreStorageSonId AS purchasePreStorageSonId")//采购预入库子件id
				.addField("PPSS.PurchasePreStorageBid AS purchasePreStorageSonBid")//采购预入库单号

				.addLeftJoin("TCW_PartnerBankInfo PB ON PB.Id = PPCI.PartnerBankInfoId ")//合作商银行账户管理表
				.addField("PPCI.PartnerBankInfoId AS partnerBankInfoId")
				.addField("PB.PartnerName AS partnerName")//供应方公司名称 、合作方名称

				.addLeftJoin("TCG_PurchaseInStorage PS ON PS.Id = B.PurchaseStorageId")//采购入库单
				.addField("PS.Bid AS purchaseStorageBid")//采购入库单号

				.addField("ISNULL(PC.ReserveNumber - AB.ParentAssembleNumber,0)  AS assembleLostNum")//母件组装缺失数量 = 母件采购数量-母件组装数量

				.where("PCI.CancelState = 1");//采购取消状态（0取消、1正常）

		return cond;
	}





}
